package org.openrbac.rbac.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.openrbac.rbac.constant.CommonConstant;
import org.openrbac.rbac.entity.User;
import org.openrbac.rbac.mapper.UserMapper;
import org.openrbac.rbac.ubean.QqUser;
import org.openrbac.rbac.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;

/**
 * @author 梁富贵
 * &#064;Date  2024/4/7
 **/
@Service
public class MailService extends ServiceImpl<UserMapper, User>{

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private JavaMailSender mailSender;

    @Autowired
    private PasswordEncoder passwordEncoder;

    //application.properties中已配置的值
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 给前端输入的邮箱，发送验证码
     * @param email
     * @param
     * @return
     */
    @Async
    public void sendMimeMail( String email) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码邮件");
            //生成随机数
            String code = randomCode();

            QqUser qqUser = new QqUser();
            qqUser.setCode(code);
            qqUser.setEmail(email);
            redisUtil.hashSet(CommonConstant.MAIL_CAPTCHA, email,qqUser,60*5);

            mailMessage.setText("您收到的验证码是："+code);

            mailMessage.setTo(email);

            mailMessage.setFrom(from);

            mailSender.send(mailMessage);

        }catch (Exception e){
            throw new RuntimeException("发送邮件失败");
        }
    }

    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    public String randomCode(){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    /**
     * 检验验证码是否一致
     * @param userVo
     * @param
     * @return
     */
    public boolean registered(QqUser userVo){

        QqUser qqUser = (QqUser) redisUtil.hashGet(CommonConstant.MAIL_CAPTCHA,userVo.getEmail());

        if(qqUser==null){
            throw new RuntimeException("验证码已过期");
        }
        String name = userVo.getUsername();
        String code = qqUser.getCode();
        String password = userVo.getPassword();
        String email = qqUser.getEmail();


        //获取表单中的提交的验证信息
        String voCode = userVo.getCode();

        //如果email数据为空，或者不一致，注册失败
        if (password == null || !code.equals(voCode) || name==null){
            return false;
        }
        QueryWrapper<QqUser> wrapper = new QueryWrapper<>();
        wrapper.ne("email",email);

        User user =new User();
        user.setUsername(userVo.getUsername());
        user.setPassword(passwordEncoder.encode(userVo.getPassword()));
        user.setEmail(userVo.getEmail());
        if(this.baseMapper.insert(user)>0){
            redisUtil.hashDelete(CommonConstant.MAIL_CAPTCHA,userVo.getEmail());

            return true;
        }
        return false;
    }
}
